<template>
  <div class='container'>

    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--   下面主体内容 -->

    <el-card class="box-card">
      <!--  标题内容 -->
      <el-row>
        <el-col :span='16'>
          <el-input placeholder="请输入搜索内容"
                    v-model="keyWords"
                    class="input-with-select">
            <!-- @blur.native.enter="change" -->

            <el-button slot="append"
                       icon="el-icon-search"> </el-button>
            <!-- @click.native="change" -->

          </el-input>

        </el-col>
        <el-col :span='8'
                class="addUsers">

          <el-button type='primary'
                     @click="dialogFormVisible=true"> 添加用户</el-button>

        </el-col>
      </el-row>

      <!--  table 内容 -->

      <!-- create_time:1486720211
email:null
id:500
mg_state:true
mobile:null
role_name:"超级管理员"
username:"admin" -->

      <el-table :data="allUsersList"
                border
                stripe
                style="width: 100%">
        <el-table-column type="index">
        </el-table-column>

        <el-table-column label="用户"
                         width="150"
                         align='center'>
          <template slot-scope="scope">

            <span style="margin-left: 10px">{{ scope.row.username }}</span>
          </template>
        </el-table-column>

        <el-table-column label="邮箱"
                         width="160">
          <template slot-scope="scope">

            <span style="margin-left: 10px">{{ scope.row.email }}</span>
          </template>
        </el-table-column>

        <el-table-column label="电话"
                         width="150">
          <template slot-scope="scope">

            <span style="margin-left: 10px">{{ scope.row.mobile }}</span>
          </template>
        </el-table-column>

        <el-table-column label="角色"
                         width="150">
          <template slot-scope="scope">

            <span style="margin-left: 10px">{{ scope.row.role_name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态"
                         width="120">
          <template slot-scope="scope">

            <el-switch v-model="scope.row.mg_state"
                       active-color="#13ce66"
                       inactive-color="#ff4949"
                       @change='changeStatus(scope.row)'>
            </el-switch>

            <!-- <span style="margin-left: 10px">{{ scope.row.mg_state }}</span> -->
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>

            <el-button size="mini"
                       type="warning"
                       @click="changeGrantRole(scope.$index, scope.row)">分配权限</el-button>
          </template>
        </el-table-column>

      </el-table>

    </el-card>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="pagenum"
                   :page-sizes="[1, 2, 5, 10]"
                   :page-size="pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>

    <!--  添加用户 弹框 -->

    <!-- // username用户名称不能为空password用户密码不能为空email邮箱可以为空mobile手机号可以为空 -->

    <!-- <el-button type="text"
               @click="dialogFormVisible = true">打开嵌套表单的 Dialog</el-button> -->

    <el-dialog title="添加用户"
               :visible.sync="dialogFormVisible">

      <el-form :model="form"
               :rules="addRules"
               ref="addUserForm">
        <el-form-item label="用户名称"
                      prop="username"
                      :label-width="formLabelWidth">
          <el-input v-model="form.username"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码"
                      prop="password"
                      :label-width="formLabelWidth">
          <el-input v-model="form.password"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱"
                      prop="email"
                      :label-width="formLabelWidth">
          <el-input v-model="form.email"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户手机"
                      prop="mobile"
                      :label-width="formLabelWidth">
          <el-input v-model="form.mobile"
                    autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- <el-button type="primary"
                   @click="addUsersBtnSure">确 定</el-button> -->

        <el-button type="primary"
                   @click="addUsersBtnSure('addUserForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!--  编辑弹框 -->

    <el-dialog title="编辑用户"
               :visible.sync="editedialogFormVisible">

      <el-form :model="editForm"
               :rules="editRules"
               ref="editUserForm">
        <el-form-item label="用户名称"
                      prop="username"
                      :label-width="formLabelWidth">
          <el-input v-model="editForm.username"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码"
                      prop="password"
                      :label-width="formLabelWidth">
          <el-input v-model="editForm.password"
                    disabled
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱"
                      prop="email"
                      :label-width="formLabelWidth">
          <el-input v-model="editForm.email"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户手机"
                      prop="mobile"
                      :label-width="formLabelWidth">
          <el-input v-model="editForm.mobile"
                    autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="editedialogFormVisible = false">取 消</el-button>
        <!-- <el-button type="primary"
                   @click="addUsersBtnSure">确 定</el-button> -->

        <el-button type="primary"
                   @click="editUsersBtnSure('editUserForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!--  分配角色弹框 -->

    <el-dialog title="分配角色"
               :visible.sync="rolesDialogFormVisible">
      <el-form>
        <el-form-item label="当前用户"
                      :label-width="formLabelWidth">
          <span> {{roleUserName}}</span>
          <!-- <el-input v-model="form.name" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="当前角色"
                      :label-width="formLabelWidth">
          <!-- <el-input v-model="form.name" autocomplete="off"></el-input> -->
          <span> {{roleName}}</span>
        </el-form-item>
        <el-form-item label="分配新角色"
                      :label-width="formLabelWidth">
          <el-select v-model="roleId"
                     placeholder="请选择新角色">
            <el-option v-for="(item,index) in rolesList"
                       :key="index"
                       :label="item.roleName"
                       :value="item.rid"></el-option>

          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="rolesDialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="sureGrantRolesBtn">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getAllUsers, addUsers, deleteUsersId, changeUserStatus, checkedUserId, editUsers,
  grantUserRole,
  getRolesList

} from '../../api';
export default {
  name: '',
  data () {



    return {
      keyWords: '',
      // tableData: [{
      //   date: '2016-05-02',
      //   name: '王小虎',
      //   address: '上海市普陀区金沙江路 1518 弄'
      // }],
      allUsersList: [],
      pagenum: 1,  // 当前页码
      total: 0,
      // currentPage4: 4,  //当前页数
      pageSize: 10,// 每页显示的条数

      // 弹框相关的属性 定义 
      dialogFormVisible: false, // 添加用户
      formLabelWidth: '120px',
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },

      // 添加用户的表单验证
      addRules: {
        username: [{
          required: true, message: '请输入用户名', trigger: 'blur'
        }],
        password: [{
          required: true, message: '请输入密码', trigger: 'blur'
        }],
        email: [{
          required: true, message: '请输入邮箱地址', trigger: 'blur'
        }, {
          type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change'
        }],
        mobile: [{
          required: true, message: '电话不能为空'
        }]
      },
      // 定义编辑用户 
      editedialogFormVisible: false,
      editForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editRules: {
        username: [{
          required: true, message: '请输入用户名', trigger: 'blur'
        }],

        email: [{
          required: true, message: '请输入邮箱地址', trigger: 'blur'
        }, {
          type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change'
        }],
        mobile: [{
          required: true, message: '电话不能为空'
        }]
      },
      // 定义分配角色数据 
      rolesList: [],
      rolesDialogFormVisible: false,

      roleId: '',
      roleName: '',
      roleUserName: '',
      id: ''


    }
  },


  watch: {
    keyWords (newVal, oldVal) {
      if (newVal == oldVal) {
        return false
      }

      // newVal ===  this.keyWords

      this.initGetUsers(newVal)

    }
  },
  methods: {

    // 初始化数据
    async initGetUsers (keyWords = '') {
      this.keyWords = keyWords
      let { data, meta } = await getAllUsers({ query: this.keyWords, pagenum: this.pagenum, pagesize: this.pageSize })
      if (meta.status != 200) return this.$message.info({ text: meta.msg })
      // console.log(data);
      this.allUsersList = data.users
      this.total = data.total
      this.pagenum = data.pagenum
    },
    //搜索功能 
    // change () {


    //   this.initGetUsers(this.keyWords)

    // },




    // 分页的方法
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val

      this.initGetUsers()

    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`);
      this.pagenum = val
      this.initGetUsers()
    },


    // // 添加用户请求  // addUsers
    async addUsersBtnSure () {
      // alert(1)
      // 1  验证表单里面的数据  用户名 密码不能为空  
      // 2  收集 填写后表单里面的数据 
      // 3  发送 axios 请求    
      // 4   根据请求后的状态密码 判断 请求 是否成功 
      // 5   失败后处理   提示用户  失败原因    
      //  6  成功后处理   1  清空 表单数据   2  关闭弹框   3  重新渲染数据
      // addUserForm

      this.$refs['addUserForm'].validate(async validate => {

        if (validate) {

          let { meta: { status }, data } = await addUsers(this.form)
          // console.log(status);
          if (status != 201) return this.$message.error(msg);
          this.form = {
            username: '',
            password: '',
            email: '',
            mobile: ''
          },
            this.dialogFormVisible = false
          this.initGetUsers()


        }

      })




    },




    // 编辑 数据
    async handleEdit (index, row) {
      // console.log(index, row);

      //1  打开弹框  
      this.editedialogFormVisible = true
      //2  根据 id 查询当前编辑的用户 
      //3  把查询到的结果重新赋值给编辑表单  
      let { data, meta: { status, msg } } = await checkedUserId({ id: row.id })
      if (status != 200) return this.$message.error(msg);
      // console.log(data);
      this.editForm.username = data.username
      this.editForm.mobile = data.mobile

      this.editForm.email = data.email
      this.editForm.id = data.id

      // console.log(this.editForm);


    },



    editUsersBtnSure () {
      this.$refs['editUserForm'].validate(async validate => {
        if (validate) {


          // console.log(this.editForm);

          let { meta: { status, msg }, data } = await editUsers(this.editForm)
          // console.log(status);

          if (status != 200) return this.$message.error(msg);
          // console.log(data);

          this.$message.success(msg);
          this.editedialogFormVisible = false
          this.initGetUsers()



        }



      })
    },








    // 删除数据
    async handleDelete (index, row) {
      console.log(index, row);
      let { id } = row
      let { meta: { status, msg } } = await deleteUsersId({ id })
      if (status != 200) return this.$message.error(msg);

      this.$message.success(msg);
      this.initGetUsers()

    },

    // 切换用户状态 
    //     id: 500
    // mg_state: true
    async changeStatus (row) {
      console.log(row);
      let params = {
        uId: row.id,
        type: row.mg_state
      }

      let { meta: { status, msg } } = await changeUserStatus(params)
      if (status != 200) return this.$message.error(msg);

      this.$message.success(msg);
      this.initGetUsers()
    },

    // 分配角色  
    async changeGrantRole (index, row) {
      // 1 打开弹框 
      // 2 渲染角色列表

      this.rolesDialogFormVisible = true;

      console.log(row);

      this.roleName = row.role_name
      this.roleUserName = row.username

      this.id = row.id


    },

    //  确定分配角色 

    async sureGrantRolesBtn () {

      let params = { id: this.id, rid: this.roleId }
      console.log(params);

      let { data } = await grantUserRole(params)
      console.log(data);
      // 重新初始化数据 
      this.initGetUsers()

    }





  },

  async mounted () {

    this.initGetUsers()

    //     id: 275
    // roleDesc: "223"
    // roleName: "法发噶士"

    getRolesList().then(res => {
      // console.log(res.data);

      let newArr = []
      res.data.filter(item => {
        let obj = {
          rid: item.id,
          roleName: item.roleName
        }

        newArr.push(obj)

      })


      // console.log(newArr);

      this.rolesList = newArr
    })



  },







}




</script>

<style scoped lang='less'>
.addUsers {
  text-align: center;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin: 10px 200px;
}
</style>